package com.inossem.warehousestorage_inossem.activity.refund_storage;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.inossem.loadandrefresh.PullToRefreshLayout;
import com.inossem.loadandrefresh.pullableview.PullableListView;
import com.inossem.utils.base.RegexUtils;
import com.inossem.utils.base.Utils;
import com.inossem.utils.listener.NoDoubleClickListener;
import com.inossem.warehousestorage_inossem.R;
import com.inossem.warehousestorage_inossem.activity.base.BaseActivity;
import com.inossem.warehousestorage_inossem.activity.refund_storage.extra.RefundStorageExtra;
import com.inossem.warehousestorage_inossem.adapter.refundStorage.RefundStorageReservedItemListAdapter;
import com.inossem.warehousestorage_inossem.bean.refundStorage.RefundStorageReservedOverviewBean;
import com.inossem.warehousestorage_inossem.bean.refundStorage.RefundStorageSaleBatchListBean;
import com.inossem.warehousestorage_inossem.dialog.DialogUtils;
import com.inossem.warehousestorage_inossem.listener.GsonBeanListener;
import com.inossem.warehousestorage_inossem.request.refundStorage.RefundStorageReservedOverviewRequest;
import com.inossem.warehousestorage_inossem.utils.ActivityUtils;
import com.inossem.warehousestorage_inossem.utils.RefundStorageUtils;
import com.inossem.warehousestorage_inossem.utils.SPUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 作者：wsy on 2017/12/26 09:58
 * <p>
 * 邮箱：445979770@qq.com
 *
 * 预留退库概览
 */

public class RefundStorageReservedOverviewActivity extends BaseActivity {

    private TextView title, nextStep;

    private PullToRefreshLayout refresh;

    private PullableListView refundStorageReservedItemList;

    private List<RefundStorageReservedOverviewBean.ReservedBodyBean.ItemListBean> allData;

    private RefundStorageReservedItemListAdapter adapter;

    private String mReservedNumber, mMaterielCode;

    @Override
    protected void onCreateImpl(Bundle savedInstanceState) {
        setContentView(R.layout.activity_refund_storage_reserved_overview);
        initView(RefundStorageReservedOverviewActivity.this);
        SPUtils.removeReservedRefundStorageInformation(RefundStorageReservedOverviewActivity.this);
    }

    @Override
    protected void onResumeImpl() {
        initData(RefundStorageReservedOverviewActivity.this);
    }

    private void initView(Activity activity) {
        title = (TextView) activity.findViewById(R.id.headerTitle);
        refundStorageReservedItemList = (PullableListView) activity.findViewById(R.id.refundStorageReservedItemList);
        refresh = (PullToRefreshLayout) activity.findViewById(R.id.refundStorageReservedItemListRefresh);
        nextStep = (TextView) activity.findViewById(R.id.nextStep);
    }

    private void initData(Activity activity) {
        title.setText(getResources().getString(R.string.activity_refund_storage_reserced_overview_title));
        ActivityUtils.initBackAndFunction(activity, getResources().getString(R.string.activity_in_storage_receive_list_title_short), new NoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {
                DialogUtils.getConfirmDialog(RefundStorageReservedOverviewActivity.this, getResources().getString(R.string.activity_in_storage_receive_overview_clear_prompt), new DialogUtils.ConfirmDialogListener() {
                    @Override
                    public void onConfirm(Dialog dialog) {
                        finish();
                    }
                }).show();
            }
        });

        refundStorageReservedItemList.setPullUpFlag(false);
        refundStorageReservedItemList.setPullDownFlag(false);
        nextStep.setOnClickListener(new NoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {
                if (checkAndUpdate(activity, refundStorageReservedItemList)) {
                    if (checkItem(activity)) {
                        Intent intent = new Intent(activity, RefundStorageReservedAddOperatorActivity.class);
                        startActivity(intent);
                    }
                }
            }
        });
        getExtra(activity);
        mMaterielCode = "";
        getData(activity);
    }

    private boolean checkItem(Context context) {
        int confirmNumber = RefundStorageUtils.getReservedRefundStorageNumber(context);
        if (confirmNumber == 0) {
            Utils.middleToast(context, getResources().getString(R.string.activity_in_storage_free_overview_at_least_one_item));
            return false;
        }
        return true;
    }

    private void getExtra(Activity activity) {
        mReservedNumber = activity.getIntent().getStringExtra(RefundStorageExtra.RESERVED_NUMBER);
    }

    private void addSaleRefundStorageItemListData(Context context, RefundStorageReservedOverviewBean.ReservedBodyBean bean, List<RefundStorageReservedOverviewBean.ReservedBodyBean.ItemListBean> refundStorageItemList, ListView listView, boolean flag) {
        if (flag) {
            adapter = new RefundStorageReservedItemListAdapter(context, bean, refundStorageItemList, mMaterielCode, new RefundStorageReservedOverviewActivity.RefundStorageReservedOverviewListener() {
                @Override
                public void onNoDoubleClickListener(String materielCode) {
                    mMaterielCode = materielCode;
                    getData(context);
                }

                @Override
                public boolean onCheckData() {
                    return checkAndUpdate(context, listView);
                }
            });
            listView.setAdapter(adapter);
        }
    }

    private boolean checkAndUpdate(Context context, ListView listView) {
        int childCount = listView.getChildCount();
        for (int i = 1; i < childCount; i++) {
            View view = listView.getChildAt(i);
            String realSerialNumber = ((TextView) view.findViewById(R.id.realSerialNumber)).getText().toString();
            String refundStorageNumber = ((EditText) view.findViewById(R.id.refundStorageNumber)).getText().toString();
            String retainDecimal = ((TextView) view.findViewById(R.id.retainDecimal)).getText().toString();
            String refundStorageNumberMax = ((TextView) view.findViewById(R.id.refundStorageNumberMax)).getText().toString();
            String batchNumber = ((TextView) view.findViewById(R.id.batchNumber)).getText().toString();
            String batchInfoJson = ((TextView) view.findViewById(R.id.batchInfoJson)).getText().toString();
            if (!TextUtils.isEmpty(refundStorageNumber) && !RegexUtils.checkDecimal(refundStorageNumber)) {
                Utils.middleToast(context, getResources().getString(R.string.view_up_frame_overview_list_serial) + realSerialNumber + getResources().getString(R.string.activity_refund_storage_picking_overview_the_number_of_restores_is_illegal));
                return false;
            }

            if (!TextUtils.isEmpty(refundStorageNumber) && RegexUtils.checkZero(refundStorageNumber)) {
                Utils.middleToast(context, getResources().getString(R.string.view_up_frame_overview_list_serial) + realSerialNumber + getResources().getString(R.string.activity_refund_storage_picking_overview_the_number_of_restores_must_be_greater_than_zero));
                return false;
            }

            if (!TextUtils.isEmpty(refundStorageNumber) &&!Utils.checkRetainDecimal(refundStorageNumber, retainDecimal)) {
                Utils.middleToast(context, context.getResources().getString(R.string.activity_in_storage_receive_overview_serial) + realSerialNumber + String.format(context.getResources().getString(R.string.common_retain_decimal_illegal), TextUtils.isEmpty(retainDecimal) ? context.getResources().getString(R.string.common_retain_decimal_unlimited) : retainDecimal));
                return false;
            }

            if (!TextUtils.isEmpty(refundStorageNumber)) {
                float maxNumber = Float.parseFloat(refundStorageNumberMax);
                float refundStorageNumberFloat = Float.parseFloat(refundStorageNumber);
                if (refundStorageNumberFloat > maxNumber) {
                    Utils.middleToast(context, getResources().getString(R.string.view_up_frame_overview_list_serial) + realSerialNumber + getResources().getString(R.string.activity_refund_storage_reserced_overview_the_number_of_restores_can_not_exceed_the_quantity_of_demand));
                    return false;
                }
            }

            RefundStorageReservedOverviewBean.ReservedBodyBean.ItemListBean reserrvedRefundStorageItem = RefundStorageUtils.getReservedRefundStorageItemBySerial(context, realSerialNumber);
            if (reserrvedRefundStorageItem != null) {
                reserrvedRefundStorageItem.setRefundNumber(refundStorageNumber);
                if (!context.getResources().getString(R.string.activity_refund_storage_sale_materiel_detail_choose_batch_number).equals(batchNumber)) {
                    if (!batchNumber.equals(getResources().getString(R.string.activity_refund_storage_reserced_materiel_detail_use_the_new_batch))) {
                        reserrvedRefundStorageItem.setBatch(batchNumber);
                        reserrvedRefundStorageItem.setBatchInfoList(new Gson().fromJson(batchInfoJson, new TypeToken<List<RefundStorageSaleBatchListBean.SaleBatchBodyBean.BatchSpecListBean>>() {
                        }.getType()));
                        reserrvedRefundStorageItem.setBatchList(new ArrayList<>());
                    }else {
                        reserrvedRefundStorageItem.setBatch(getResources().getString(R.string.activity_refund_storage_reserced_materiel_detail_use_the_new_batch));
                        reserrvedRefundStorageItem.setBatchInfoList(new ArrayList<>());
                    }
                }
                RefundStorageUtils.updateReservedRefundStorageItem(context, reserrvedRefundStorageItem);
            }
        }
        String remarkStr = ((EditText) listView.getChildAt(0).findViewById(R.id.remark)).getText().toString();
        RefundStorageUtils.updateReservedRefundStorageRemark(context, remarkStr);
        return true;
    }

    private void getData(Context context) {
        String refundStorageInformation = SPUtils.getReservedRefundStorageInformation(context);
        if (TextUtils.isEmpty(refundStorageInformation)) {
            RefundStorageReservedOverviewRequest.request(context, mReservedNumber, new GsonBeanListener<RefundStorageReservedOverviewBean>() {
                @Override
                public void onSuccess(RefundStorageReservedOverviewBean bean) {
                    //记录批次信息长度
                    List<RefundStorageReservedOverviewBean.ReservedBodyBean.ItemListBean> list = bean.getBody().getItem_list();
                    for (RefundStorageReservedOverviewBean.ReservedBodyBean.ItemListBean b:list){
                        b.setBatch_material_spec_list_long(String.valueOf(b.getBatch_material_spec_list().size()));
                    }
                    RefundStorageUtils.saveReservedRefundStorageOverviewBean(context, bean);
                    RefundStorageReservedOverviewBean.ReservedBodyBean data = bean.getBody();
                    allData = bean.getBody().getItem_list();
                    addSaleRefundStorageItemListData(context, data, ActivityUtils.getShowData(allData, 0), refundStorageReservedItemList, true);
                }
            });
        } else {
            Gson gson = new Gson();
            RefundStorageReservedOverviewBean bean = gson.fromJson(refundStorageInformation, RefundStorageReservedOverviewBean.class);
            if (TextUtils.isEmpty(mMaterielCode)) {
                allData = bean.getBody().getItem_list();
            } else {
                allData = RefundStorageUtils.getReservedRefundStorageMaterielList(context, mMaterielCode);
            }
            addSaleRefundStorageItemListData(context, bean.getBody(), ActivityUtils.getShowData(allData, 0), refundStorageReservedItemList, true);
        }

    }

    public interface RefundStorageReservedOverviewListener {
        void onNoDoubleClickListener(String materielCode);

        boolean onCheckData();
    }

    @Override
    public void onBackPressed() {
        DialogUtils.getConfirmDialog(RefundStorageReservedOverviewActivity.this, getResources().getString(R.string.activity_receive_receive_item_back_clean), new DialogUtils.ConfirmDialogListener() {
            @Override
            public void onConfirm(Dialog dialog) {
                finish();
            }
        }).show();
    }
}
